<?php

namespace App\Controller;

use app\BaseController;
use think\Token;

class User extends BaseController
{
    protected $expire_time = 2 * 60 * 60;    //token有效1小时
    public function __construct(\think\App $app, Token $token)
    {
        $this->app = $app;
        $this->request = $this->app->request;
        $this->token = $token;

        $this->UserModel = new \app\common\model\User;
        $this->RankModel = new \app\common\model\Rank;
        $this->ProjectModel = new \app\common\model\Project;
        $this->RelevanceModel = new \app\common\model\Relevance;
    }

    // 账号注册,仅超管可用
    public function register()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', '', 'trim');
            $username = $this->request->param('username', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $staffname = $this->request->param('staffname', '', 'trim');
            $rankid = $this->request->param('rankid', '', 'trim');

            $userInfo = $this->UserModel->where('id', $userid)->find();
            if (empty($userInfo)) {
                return json(error_ful('您的账号无权限'));
            }
            // 判断账号权限
            $rankId = $userInfo['rankid'];
            $auth = $this->RankModel->where('id', $rankId)->value('weigh');
            if ($auth !== '99') {
                return json(error_ful('您的账号无权限'));
            }

            // 检查要新增的账号是否存在
            $check = $this->UserModel->where('username', $username)->find();
            if (!empty($check)) {
                return json(error_ful('该账号已存在'));
            }




            if (empty($username) || empty($password)) {
                return json(error_ful('请输入账号和密码'));
            }
            if (strlen($username) < 4) {
                return json(error_ful('账号长度不应小于4位'));
            }
            if (strlen($password) < 6) {
                return json(error_ful('密码长度不应小于6位'));
            }

            if (empty($rankid)) {
                $rankid = $this->RankModel->where('weigh', '1')->value('id');
            }

            // return json(error_ful('可用'));
            // 生成密码盐
            $salt = bin2hex(random_bytes(16));  // 生成32位随机salt 
            // 密码加密
            $password = md5($salt . $password);

            $data = [
                'username' => $username,
                'password' => $password,
                'salt' => $salt,
                'staffname' => $staffname,
                'rankid' => $rankid,
                'createtime' => time()
            ];


            $addStatus = $this->UserModel->insert($data);

            if ($addStatus === false) {
                return json(error_ful('新增账号失败'));
            } else {
                return json(success_ful('新增账号成功'));
            }
        }
    }

    // 账号登录
    public function sign()
    {
        if ($this->request->isPost()) {
            $username = $this->request->param('username', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $token = $this->request->param('token', '', 'trim');
            if (!empty($token)) {
                $userInfo = $this->token->checkToken($token);
                if ($userInfo['status'] === 0) {
                    return json(error_ful($userInfo['message']));
                }
                
                $newToken = $this->token->createToken($userInfo['data'], $this->expire_time);
                return json(success_ful('刷新token',['token' => $newToken]));
            }

            $userInfo = $this->UserModel
                ->with('rank')
                ->where('username', $username)
                ->find();
            if (empty($userInfo)) {
                return json(error_ful('账号不存在'));
            }

            $salt = $userInfo['salt'];

            $password = md5($salt . $password);

            if ($password === $userInfo['password']) {
                unset($userInfo['password']);
                unset($userInfo['salt']);
                unset($userInfo['rankid']);
                unset($userInfo['jobid']);
                unset($userInfo['rank']['id']);
                unset($userInfo['rank']['status']);
                $token = $this->token->createToken($userInfo, $this->expire_time);

                $data = [
                    'user' => $userInfo,
                    'token' => $token
                ];
                return json(success_ful('登录成功', $data));
            } else {
                return json(error_ful('账号或密码错误'));
            }
        }
    }

    // 账号列表，超管和管理员可用
    public function list()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0, 'trim');
            $proid = $this->request->param('proid', 0, 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 25, 'trim');
            $sort = $this->request->param('sort', 'createtime', 'trim');
            $by = $this->request->param('by', 'desc', 'trim');

            // 偏移量
            $offset = ($page - 1) * $limit;

            $userInfo = $this->UserModel->where('id', $userid)->find();
            if (empty($userInfo)) {
                return json(error_ful('账号不存在'));
            }



            $where = [
                'deletetime' => null,
            ];

            // 判断是否以文件夹查找
            if (!empty($proid)) {
                $proInfo = $this->RelevanceModel->where(['proid' => $proid, 'userid' => $userid])->find();
                if (empty($proInfo)) {
                    return json(error_ful('项目不存在'));
                }
                // 判断当前账号是否有权限
                if ($proInfo['auth'] !== '4') {
                    return json(error_ful('当前账号无权限'));
                }

                $where['proid'] = $proid;
                $count = $this->RelevanceModel
                    ->with('user')
                    ->where($where)
                    ->count();
                if ($count <= 0) {
                    return json(error_ful('暂无数据'));
                }
                $userList = $this->RelevanceModel
                    ->with('user')
                    ->where($where)
                    ->order($sort, $by)
                    ->limit($offset, $limit)
                    ->select();

                // 去除密码和密码盐
                foreach ($userList as $item) {
                    unset($item['user']['password']);
                    unset($item['user']['salt']);
                }

            } else {
                $weigh = $this->RankModel->where('id', $userInfo['rankid'])->value('weigh');
                if ($weigh === '1') {
                    return json(error_ful("您的账号无权限"));
                }
                $count = $this->UserModel
                    ->where($where)
                    ->count();
                if ($count <= 0) {
                    return json(error_ful('暂无账号'));
                }
                $userList = $this->UserModel
                    ->with('rank')
                    ->where($where)
                    ->order($sort, $by)
                    ->limit($offset, $limit)
                    ->select();

                // 去除密码和密码盐
                foreach ($userList as $item) {
                    unset($item['password']);
                    unset($item['salt']);
                }

            }

            $data = [
                'count' => $count,
                'userList' => $userList
            ];
            return json(success_ful('账号列表', $data));
        }
    }

    // 修改账号信息,仅超管可用
    public function update()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0, 'trim');
            $username = $this->request->param('username', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $newpassword = $this->request->param('newpassword', '', 'trim');

            // 检查修改的账号是否存在
            if ($userid <= 0) {
                return json(error_ful('未发现账号'));
            }
            $userInfo = $this->UserModel->where('id', $userid)->find();
            if (empty($userInfo)) {
                return json(error_ful('未发现账号'));
            }

            $data = [

            ];

            // 判断身份等级
            if (!empty($rankid)) {
                $rankInfo = $this->RankModel->where('id', $rankid)->find();
                if (empty($rankInfo)) {
                    return json(error_ful('身份等级不存在'));
                }
                if ($rankInfo['weigh'] === '99') {
                    return json(error_ful('超级管理员账号有且只能有一个'));
                }
                $data['rankid'] = $rankid;
            }

            $originalUsername = $userInfo['username']; // 原用户名
            if (!empty($username) && $username !== $originalUsername) {
                $userOther = $this->UserModel
                    ->where('id', '<>', $userid)
                    ->where('username', '=', $username)
                    ->find();

                if (!empty($userOther)) {
                    return json(error_ful('账号重复'));
                }
                $data['username'] = $username;
            }

            if (!empty($password)) {
                // 生成密码盐
                $salt = bin2hex(random_bytes(16));  // 生成32位随机salt 
                $password = md5($salt . $password);
                $data['password'] = $password;
                $data['salt'] = $salt;
            }

            // 姓名不为空
            if (!empty($staffname)) {
                $data['staffname'] = $staffname;
            }

            $status = $this->UserModel->where('id', $userid)->update($data);

            if ($status === false) {
                return json(error_ful('修改失败,数据库错误'));
            } elseif ($status == 0) {
                return json(error_ful('没有修改任何信息'));
            } else {
                return json(success_ful('修改成功'));
            }

        }
    }

    // 刷新token
    public function newtoken()
    {
        if ($this->request->isPost) {

        }
    }

}